package cn.turboinfo.fuyang.api.gateway.mini.framework.http.interceptor;

import cn.turboinfo.fuyang.api.gateway.mini.framework.http.context.MiniRequestContextHolder;
import cn.turboinfo.fuyang.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MiniRequestContextInterceptor extends BaseHandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("收到请求: {}", request.getRequestURI());
        String referer = request.getHeader("referer");
        if (referer.isBlank() || !referer.startsWith("https://servicewechat.com/")) {
            return false;
        }
        MiniRequestContextHolder.reset();
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        MiniRequestContextHolder.reset();
        log.debug("结束请求: {}", request.getRequestURI());
    }

}
